package com.windy.service;

import com.windy.app.vo.Token;
import com.windy.exection.TokenException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Component
public class TokenService {

    @Resource
    RedisService redisService;

    public Token getToken(){
        Token token = new Token(UUID.randomUUID().toString());
        redisService.setEx(token.getToken(),token,10000L);
        return token;
    }

    public boolean checkToken(HttpServletRequest request) throws TokenException {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = request.getParameter("token");
            if (StringUtils.isEmpty(token)){
                throw new TokenException("token不存在！");
            }
        }
        if(!redisService.exists(token)){
            throw new TokenException("重复的操作！");
        }
        boolean remove = redisService.remove(token);
        if (!remove){
            throw new TokenException("重复的操作！");
        }
        return true;
    }
}
